package org.railage.server.services;

import java.util.Arrays;
import java.util.List;

import org.railage.common.protocol.Result;
import org.railage.server.dao.RouteDAO;
import org.railage.server.dao.RouteDAOImpl;
import org.railage.server.entities.Route;
import org.railage.server.util.HibernateUtil;
import org.railage.server.util.Utils;

public class RouteService {

	private RouteDAO routeDAO = new RouteDAOImpl();

	public Result addRoute(Object obj) {
		Object[] params = (Object[]) obj;

		String routeName = (String) params[0];
		String[] stationsArr = (String[]) params[1];
		String[] timesAfterPrevArr = (String[]) params[2];
		String[] timesOnStationsArr = (String[]) params[3];

		String stations = Utils.implode(",", stationsArr);
		String timesAfterPrev = Utils.implode(",", timesAfterPrevArr);
		String timesOnStations = Utils.implode(",", timesOnStationsArr);

		Result result = null;
		int resultCode = routeDAO.addRoute(routeName, stations, timesAfterPrev,
				timesOnStations);
		switch (resultCode) {
		case 0:
			result = new Result(true, "Route " + routeName + " added");
			break;
		case 1:
			result = new Result(false, "Route " + routeName + " already exists!");
			break;
		case -1:
			result = new Result(false, HibernateUtil.DB_SESSION_ERROR_MSG);
			break;
		default:
			break;
		}
		return result;
	}

	public Result deleteRoute(Object obj) {
		String routeName = (String) obj;
		Result result = null;
		int resultCode = routeDAO.deleteRoute(routeName);
		switch (resultCode) {
		case 0:
			result = new Result(true, "Route " + routeName + " deleted");
			break;
		case 1:
			result = new Result(false, "There are trips on route " + routeName + "! Cannot delete!");
			break;
		case -1:
			result = new Result(false, HibernateUtil.DB_SESSION_ERROR_MSG);
			break;
		default:
			break;
		}
		return result;
	}

	public String[] getRouteNames(Object obj) {
		List<Route> routes = routeDAO.getAllRoutes();
		String[] routeNames = new String[routes.size()];
		int i = 0;
		for (Route route : routes) {
			routeNames[i] = route.getName();
			i++;
		}
		Arrays.sort(routeNames);
		return routeNames;
	}

	public String getRouteByTripID(Object obj) {
		return routeDAO.getRouteByTripID((Integer) obj).getName();
	}
}
